package com.yd.mvc.mobile.messageController;

import com.yd.app.service.common.LoggerService;
import com.yd.app.service.mobile.messageService.MMessageService;
import com.yd.app.util.BusinessException;
import com.yd.domain.business.Message;
import com.yd.domain.commom.PageModel;
import com.yd.domain.searchParam.MessageReturnParam;
import com.yd.domain.sys.Logger;
import com.yd.domain.sys.PermEnum;
import com.yd.domain.sys.User;
import com.yd.mvc.baseController.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author zy
 * @create 2018-03-13 10:09
 * @desc
 **/
@RestController
@RequestMapping(value = "/mapi/mmsg")
public class MMessageController extends BaseController{
    @Autowired
    private MMessageService messageService;
    @Autowired
    private LoggerService loggerService;
    /**
     * @Author: zy
     * @Desc: 录入信息
     * @Date:  2018/3/13
     * @Param
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public void addMessage(@RequestBody Message message,HttpServletRequest request)  {
        String addUser= message.getPublishUser();
        String suff="发起人:"+addUser+";接收人:"+message.getReceiveUser()+";内容:"+message.getContent();
        try {
            messageService.addMessage(message);
            loggerService.addLogger(new Logger("新增信息记录",addUser,Logger.LOG_TYPE.ADD,Logger.STATUS.SUCCESS,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
        } catch (Exception e) {
            loggerService.addLogger(new Logger("新增信息记录",addUser,Logger.LOG_TYPE.ADD,Logger.STATUS.FAIL,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
            e.printStackTrace();
        }
    }
    /**
     * @Author: zy
     * @Desc: 修改信息
     * @Date:  2018/3/13
     * @Param
     */
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public void updateMessage(@RequestBody Message message,HttpServletRequest request){
        String updateUser="admin";
        String suff="发起人:"+updateUser+";接收人:"+message.getReceiveUser()+";内容:"+message.getContent();
        try {
            messageService.updateMessage(message);
            loggerService.addLogger(new Logger("修改信息记录",updateUser,Logger.LOG_TYPE.UPDATE,Logger.STATUS.SUCCESS,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
        } catch (Exception e) {
            e.printStackTrace();
            loggerService.addLogger(new Logger("修改信息记录",updateUser,Logger.LOG_TYPE.UPDATE,Logger.STATUS.FAIL,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
        }
    }
    /**
     * @Author: zy
     * @Desc: 删除消息
     * @Date: 2018/3/13
     * @Param
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public void deleteMessage(@PathVariable("id") String id,HttpServletRequest request){
        String delUser="admin";
        String suff="删除人："+delUser+",删除的id:"+id+",删除时间："+new Date();
        try {
            messageService.deleteMessage(id);
            loggerService.addLogger(new Logger("删除信息记录",delUser,Logger.LOG_TYPE.DELETE,Logger.STATUS.SUCCESS,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
        } catch (Exception e) {
            e.printStackTrace();
            loggerService.addLogger(new Logger("删除信息记录",delUser,Logger.LOG_TYPE.DELETE,Logger.STATUS.FAIL,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
        }
    }

    /**
     * 删除交谈信息
     * @param token
     * @param session
     */
    @RequestMapping(value = "/deleteTalk/{token}", method = RequestMethod.DELETE)
    public void deleteTalk(@PathVariable("token") String token,HttpSession session) throws BusinessException {
        User u = (User) session.getAttribute("login_user");
        if(u!=null){
            messageService.deleteTalk(token);
        }else{
            throw new BusinessException(401,"尚未登录","no-login");
        }
    }

    /**
     * @Author: zy
     * @Desc: 数据列表
     * @Date:  2018/3/9
     * @Param
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public List<MessageReturnParam> getMessageList( HttpSession session) throws BusinessException {
        //前台处理token的拼接，两个ID
        User u = (User) session.getAttribute("login_user");

        List<MessageReturnParam> list=new ArrayList<>();
        if(u!=null){
            if(u.getPermCodeList()!=null){
                if(u.getPermCodeList().contains(PermEnum.MESSAGE_MANAGER)){//是否具有消息管理权限
                    list=messageService.getMessageForListWithManager(u.getId());

                }else{
                    list=messageService.getMessageForList(u.getId());
                }
            }else{
                list=messageService.getMessageForList(u.getId());
            }
        }else{
            throw new BusinessException(401,"尚未登录","no-login");
        }
        Collections.sort(list, new Comparator<MessageReturnParam>() {
            @Override
            public int compare(MessageReturnParam o1, MessageReturnParam o2) {
                if(o1.getLastMessage()!=null&&o2.getLastMessage()!=null){
                    if(o1.getLastMessage().getPublishTime().getTime()-o2.getLastMessage().getPublishTime().getTime()>0){
                        return -1;
                    }else if(o1.getLastMessage().getPublishTime().getTime()-o2.getLastMessage().getPublishTime().getTime()<0){
                        return 1;
                    }else{
                        return 0;
                    }
                }else if(o1.getLastMessage()==null&&o2.getLastMessage()!=null){
                    return 1;
                }else if(o1.getLastMessage()!=null&&o2.getLastMessage()==null){
                    return -1;
                }else{
                    return 0;
                }
            }
        });
        return list;
    }

    /**
     * 获取谈话记录
     * @return
     */
    @RequestMapping(value = "/talk/list/{token}/{pageIndex}/{pageSize}", method = RequestMethod.GET)
    public PageModel getMessageTalkList(HttpSession session,@PathVariable("token")String token,@PathVariable("pageIndex")int pageIndex,@PathVariable("pageSize")int pageSize) throws BusinessException {
        //前台处理token的拼接，两个ID
        User u = (User) session.getAttribute("login_user");
        PageModel pm=messageService.getMessageTalkForList(token,pageIndex,pageSize);
        //数据获取成功---更新已读状态
        if(u!=null){
            messageService.updateMessageIfRead(u.getId(),token,true);
        }else{
            throw new BusinessException(401,"尚未登录","no-login");
        }
        return pm;
    }
    /**
     * 获取当前未读消息数量
     * @return
     */
    @RequestMapping(value = "/talk/notRead", method = RequestMethod.GET)
    public int getNoReadMessageCount(HttpSession session) throws BusinessException {
        //前台处理token的拼接，两个ID
        User u = (User) session.getAttribute("login_user");
        int count=0;
        if(u!=null){
            count=messageService.getNoReadMessageCount(u.getId());
        }else{
            throw new BusinessException(401,"尚未登录");
        }
        return count;
    }

    /**
     * @Author: zy
     * @Desc: 批量删除
     * @Date:  2018/3/13
     * @Param
     */
    @RequestMapping(value = "/deleteAll",method = RequestMethod.POST)
    public void deleteAll(@RequestBody Message message,HttpServletRequest request){
        String delUser="admin";//后台自动获取，currentUser中；
        String suff="删除人："+delUser+",批量删除的id:"+message.getStrMsg()+"删除时间："+new Date();
        try {
            String str=message.getStrMsg();
            String strN= str.substring(0,str.length()-1);//上面这两行代码是为了去除前台传过来的id字符串中最后一个多余的 "，"
            message.setStrMsg(strN);
            messageService.deleteAll(message);
            loggerService.addLogger(new Logger("批量删除信息记录",delUser,Logger.LOG_TYPE.DELETE,Logger.STATUS.SUCCESS,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
        }catch (Exception e){
            loggerService.addLogger(new Logger("批量删除信息记录",delUser,Logger.LOG_TYPE.DELETE,Logger.STATUS.FAIL,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
            e.printStackTrace();
        }
    }
    /**
     * @Author: zy
     * @Desc: 获取所有的客服人员
     * @Date:  2018/4/9
     * @Param
     */
    @RequestMapping(value = "/getAllCustomService",method = RequestMethod.GET)
    public List<User> getAllCustomService(){
        List<User> list;
        list=messageService.getAllCustomService();
        if(list==null){
            list=new ArrayList<>();
        }
        return list;
    }
    /**
     * @Author: zy
     * @Desc: 获取对话的token
     * @Date:  2018/4/9
     * @Param
     */
    @RequestMapping(value = "/getToken/{userId}", method = RequestMethod.GET)
    public String getMessageTalkList(HttpSession session,@PathVariable("userId")String userId) throws BusinessException {
        String token="";
        User u = (User) session.getAttribute("login_user");
        if(u!=null){
            token=messageService.getToken(u.getId(),userId);
        }else{
            throw new BusinessException(401,"尚未登录","no-login");
        }
        return token;
    }

    /**
     * 获取是否存在最新消息
     * @param token
     * @return
     */
    @RequestMapping(value = "/ifMsg/{token}", method = RequestMethod.GET)
    public boolean getIfMsg(@PathVariable("token")String token, HttpSession session) throws BusinessException {
        //前台处理token的拼接，两个ID
        User u = (User) session.getAttribute("login_user");
        boolean ifMsg=false;
        if(u!=null){
            ifMsg=messageService.getIfMsg(token,u.getId());
        }else{
            throw new BusinessException(401,"尚未登录","no-login");
        }
        return ifMsg;
    }
    /**
     * 获取最新消息未读消息
     * @param token
     * @return
     */
    @RequestMapping(value = "/lastMsg/{token}", method = RequestMethod.GET)
    public List<Message> lastMsg(@PathVariable("token")String token, HttpSession session) throws BusinessException {
        //前台处理token的拼接，两个ID
        User u = (User) session.getAttribute("login_user");
        List<Message> list=new ArrayList<>();
        if(u!=null){
            list=messageService.lastMsg(token,u.getId());
        }else{
            throw new BusinessException(401,"尚未登录","no-login");
        }
        return list;
    }
}
